package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/rw555/fdsmastergo/internal/config"
	"gitee.com/rw555/fdsmastergo/pkg/logger"
	"gitee.com/rw555/fdsmastergo/pkg/version"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	_ "modernc.org/sqlite"
)

func main() {
	// 初始化日志
	if err := logger.Configure(logger.Config{
		EnableConsole:       true,
		EnableCaller:        true,
		LogDirByServiceName: "config_server",
		MaxSize:             1,
		MaxBackups:          3,
		MaxAge:              3,
		SystemLogLevel:      zapcore.InfoLevel,
		OperationLogLevel:   zapcore.InfoLevel,
		NetworkLogLevel:     zapcore.InfoLevel,
		OtherLogLevel:       zapcore.DebugLevel,
	}); err != nil {
		fmt.Printf("初始化日志失败: %v\n", err)
		os.Exit(1)
	}
	defer logger.Sync()

	// 输出版本信息
	vInfo := version.NewInfo("config_server")
	logger.SystemInfo("配置服务启动",
		zap.String("version", vInfo.Version),
		zap.String("gitCommit", vInfo.GitCommit),
		zap.String("buildTime", vInfo.BuildTime),
		zap.String("platform", vInfo.Platform))

	// 初始化服务
	storage, err := config.NewConfigStorage()
	if err != nil {
		logger.SystemError("创建配置存储失败", zap.Error(err))
		return
	}
	defer storage.CloseDB()

	// 创建HTTP处理程序
	handler := config.NewHandler(storage)

	// 设置路由
	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Recovery())

	// API 路由
	v1 := r.Group("/api/v1")
	{
		v1.POST("/configs/get", handler.GetConfig)              // 获取完整配置
		v1.POST("/configs/update/all", handler.UpdateAllConfig) // 更新完整配置
		v1.POST("/configs/update", handler.UpdateConfig)        // 更新一条配置

		// 自动模式会话记录相关API
		v1.POST("/auto-mode/sessions/query", handler.HandleGetAutoModeSessions) // 查询自动模式会话记录
		v1.POST("/auto-mode/sessions", handler.HandleSaveAutoModeSession)       // 保存自动模式会话记录
	}

	// 创建HTTP服务
	srv := &http.Server{
		Addr:    "0.0.0.0:8082", // 监听所有网络接口
		Handler: r,
	}

	// 启动HTTP服务
	go func() {
		logger.SystemInfo("配置服务启动", zap.String("port", srv.Addr))
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.SystemError("启动服务失败",
				zap.Error(err))
		}
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	logger.SystemInfo("正在关闭服务...")

	// 创建一个5秒超时的上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 优雅关闭服务
	if err := srv.Shutdown(ctx); err != nil {
		logger.SystemError("服务关闭异常",
			zap.Error(err))
	}

	logger.SystemInfo("服务已关闭")
}
